#pragma once
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>

// 宏替换, 打印错误信息
// “\”是续行符
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

const int defaultid = -1;
const int gsize = 4096;
const std::string pathname = ".";
const int projid = 0x66; // 项目id
const int gmode = 0666;
// 用户类型
#define CREATER "creater"
#define USER "user"

class Shm
{
private:
    // 设置帮助函数(有代码块重复)
    void CreateHelper(int flag)
    {
        printf("key: 0x%x\n", _key); // 16 进制能直观展示 key 的位组合结构
        // 共享内存的生命周期随内核
        _shmid = shmget(_key, _size, flag);
        if (_shmid < 0)
        {
            ERR_EXIT("shmget");
        }
        printf("shmid: %d\n", _shmid); // 10进制打印, shmid是长整数
    }
    // 创建一个全新的IPC
    void Create()
    {
        CreateHelper(IPC_CREAT | IPC_EXCL | gmode);
    }
    void Attach()
    {
        _start_mem = shmat(_shmid, nullptr, 0);
        if ((long long)_start_mem < 0)
        {
            ERR_EXIT("shmat");
        }
        printf("attach success\n");
    }
    // 去关联
    void Detach()
    {
        int n = shmdt(_start_mem);
        if(n == 0)
        {
            printf("shmdt success\n");
        }
    }

    void Destory()
    {
        // if (_shmid == defaultid)
        //     return;
        int n = shmctl(_shmid, IPC_RMID, nullptr);
        if (n > 0)
        {
            printf("shmctl delete shm : %d success\n", _shmid);
        }
        else
        {
            ERR_EXIT("shmctl");
        }
    }

public:
    Shm(const std::string &pathname, int projid, const std::string &usertype)
        : _shmid(defaultid),
          _size(gsize),
          _start_mem(nullptr),
          _usertype(usertype)
    {
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0)
        {
            ERR_EXIT("ftok");
        }

        if(_usertype == CREATER)
            Create(); // 初始化时直接创建
        else if(_usertype == USER)
            Get();

        Attach(); // 挂接
    }
    // 获取共享内存
    void Get()
    {
        CreateHelper(IPC_CREAT);
    }

    int Size()
    {
        return _size;
    }

    void *VirtualAddr()
    {
        printf("VirtualAddr : %p\n", _start_mem);
        return _start_mem;
    }

    ~Shm()
    {
        Detach(); // 去关联
        if(_usertype == CREATER)
            Destory();
    }

private:
    int _shmid;
    key_t _key;
    int _size;
    void *_start_mem;
    std::string _usertype; // 用户类型
};
